<template>
<dl class="normal-bg-t" v-on:click="open()">
   <dd class="picktime-time"><span>到店时间：</span></dd>
   <dd>
       <input type="button" id="gotoStore" class="gostore-time" placeholder="请选择时间"  value="{{{initValue}}}" ca="P_确认订单$选择时间">
       <span class="sf-arrow-right"></span>
   </dd>
</dl>
<mt-popup :visible.sync="popupVisible" position="bottom" class="mint-datetime">
  <mt-picker
    :slots="slots"
    @change="onChange"
    :visible-item-count="7"
    class="mint-datetime-picker"
    ref="picker"
    show-toolbar>
 		<div class="picktime-title">
    	<div class="mint-datetime-action mint-datetime-cancel" @click="cancel" ca="P_确认订单$选择时间$取消">{{{cancelText }}}</div>
    	<div class="picktime-content">选择日期</div>
    	<div class="mint-datetime-action mint-datetime-confirm" @click="confirm" ca="P_确认订单$选择时间$确定">{{{confirmText}}}</div>
    </div>  
</mt-picker>
</mt-popup>
</template>

<style  lang="scss" scoped>
  @import '../../assets/css/_functions.scss';
  @import '../../assets/css/_variables.scss';
  .picktime-time {
  	width: rem(100) !important;
  }
  .mint-popup-bottom {
      width: rem(375);
  }

  .normal-bg-t{
      background-color: $_fff;
      font-size:rem(14);
  }
  .normal-bg-t {
        clear:both;
        overflow: hidden;
        height: rem(55);
        line-height: rem(55);

        margin:0 rem(20);
        border-bottom: 1px solid #c9d5e0;
        dd{
           float:left;
        }
        dd:last-child{float: right;}    
       /*  dl:last-child{
            border-bottom: 0
        } */
    }
    .gostore-time {
        background: 0;
        border: none 0;    
        font-size: rem(14);    
    }
    .sf-arrow-right {
      display: inline-block;
      vertical-align: middle;
      // margin-top:0.2rem;

    }
    
    .picker  {
      .picker-toolbar {
        height: rem(50);
        font-size: rem(14);
        background: $_fafbfc;
        line-height: rem(50);
      } 
    }  
    .picktime-title {
      height: rem(40);
      line-height: rem(40);
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      font-size: rem(16);
      .mint-datetime-cancel {
        padding-left: rem(18);
        flex:2;
        text-align: left;
      }
      .mint-datetime-confirm {
        padding-right: rem(18);
        text-align: right;

      }
      .mint-datetime-action {
        color: $_0c7cfe;
        flex:2;

      }
      .picktime-content {
        font-size: rem(18);
        text-align: center;
        flex:8;
      }
    }
</style>

<script>
import Vue from 'vue';
/*import { DatetimePicker } from 'mint-ui';*/

import { Popup } from 'mint-ui';

Vue.component(Popup.name, Popup);
import { Picker } from 'mint-ui';

Vue.component(Picker.name, Picker);

var opt={
  num: 8, //默认显示后8天(包含今天)
  sDate:new Date() //开始日期, date对象
};
 
export default {
    props: {
      cancelText: {
        type: String,
        default: '取消'
      },
      confirmText: {
        type: String,
        default: '确定'
      },
      // currentTime:{
      //    type: Object,
      //    default: function () {
      //       return new Date();
      //    }
      // },
      chooseTime:{
        type:String,
        default:""
      },
      num:{
        type:Number,
        default:8
      }
    },
    data() {
      return {
        //设置初始化slot
        slots:[{
            flex:1,
            values:[],
            className: 'slot1',
            textAlign: 'center',
            defaultIndex:0
            //defaultIndex:parseInt(sessionStorage.getItem("defaultIndex"))?parseInt(sessionStorage.getItem("defaultIndex")):this.defaultIndex
          }, {
            flex: 1,
            values: ["上午","下午"],
            className: 'slot2',
            textAlign: 'center',
            defaultIndex:0
        }],
        popupVisible: false, //弹框的显示和隐藏
        currentValue:'', //当前时间值
        initValue:'', //初始化值
        fullDaysArr:"",  //时间数组
        remark:"上午", //选择时间的上午还是下午
        currentTime:'', //当前时间
        defaultIndex:'', //默认索引
        /*//dataArr : this.getDaysArr(opt.num), //获取所有日期数据集合(数组)
        index: 1, //取得当前选中日期的索引
        index_2: 0,
        daysArr:['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
        daysArrW:['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
        dayAp:['上午', '下午', '需门店确认'],
        count: 0//到店时间重置次数*/
        isscode:false //是否是特殊轮胎scode;
      }
    },
    ready(){
    },
    events: {
        'sendTime':function(t){
            this.currentTime = t[0];
            var data = this.dataNumber(t[0]);
            var time = new Date(data);
            this.currentTime = time;
            var h = time.getHours();
            this.slots[0].values = this.getDaysArr(this.num);
            if(t[1]){
              this.isscode = true;
            }
            if(h<16){
              if(!this.isscode){
                this.initValue = this.getDate(time,1)+" 上午";
                this.slots[0].defaultIndex=1;
                this.defaultIndex = 1;
              }else{
                  this.initValue = this.getDate(time,3)+" 上午";
                this.slots[0].defaultIndex=3;
                this.defaultIndex = 3;
              }
            }else{
              if(!this.isscode){
                this.initValue = this.getDate(time,2)+" 上午";
                this.slots[0].defaultIndex=2;
                this.defaultIndex = 2;
              }else{
                 this.initValue = this.getDate(time,4)+" 上午";
                this.slots[0].defaultIndex=4;
                this.defaultIndex = 4;
              }
            }
            
            this.fullDaysArr = this.getFullDaysArr(this.num);
            //选择时间
            var defaultIndex = sessionStorage.getItem("defaultIndex")?sessionStorage.getItem("defaultIndex"):this.defaultIndex;
            this.chooseTime = this.fullDaysArr[defaultIndex].replace(/([^\u0000-\u00FF])/g,'/');

            var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
            if(reg.test(this.fullDaysArr[this.defaultIndex])){
              var str = this.fullDaysArr[this.defaultIndex].replace(/([^\u0000-\u00FF])/g,'/');
              str = str.substring(0,str.length-1);

            }else{
              var str = this.fullDaysArr[this.defaultIndex].replace(/([^\u0000-\u00FF])/g,'/');
            }

            sessionStorage.setItem("fullday",str);
            sessionStorage.setItem('remark','上午');
            //this.$dispatch("chooseTime-dispatch");
           
         }
         /*'chooseTime-'(){    
             // this.chooseTime = this.fullDaysArr[this.defaultIndex];
         },*/
         
    },
    methods: {
    	dataNumber:function(time){
				var time = time.substring(0,19);    
				time = time.replace(/-/g,'/'); 
				var timestamp = new Date(time).getTime();
				return timestamp;
			},
    	timestamp: function ( time ){
				var date = new Date(time);
				var Y = date.getFullYear() + '.';
				var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '.';
				var week='';
				var D = date.getDate() + ' ';
				switch (date.getDay()) {
				  case 0:week="星期天";break
				  case 1:week="星期一";break
				  case 2:week="星期二";break
				  case 3:week="星期三";break
				  case 4:week="星期四";break
				  case 5:week="星期五";break
				  case 6:week="星期六";break
				}
				return M+D+week;
			},


        setInputVal(){
            //this.$parent.$refs.coupon.chooseTime = this.fullDaysArr[this.defaultIndex];
        },
         //获取年月的数组
        getFullDaysArr(num){
          var arr = [];
          for(var i=0;i<num;i++){
             arr.push(this.getFullDate(this.currentTime,i));
          };
          return arr;
        },
        //获取年月日
        getFullDate(date,days){
           var d = new Date(date);
           d.setDate(d.getDate() + days);
           var s =  d.toLocaleDateString();
           return s;
        },
        //获取时间数组
        getDaysArr(num) {
            var arr = [];
            for (var i = 0; i < num; i++) {
                arr.push(this.getDate(this.currentTime, i));
            };
            return arr;
        },

        //获取时间
        getDate(date, days) {
            var d = new Date(date);
            d.setDate(d.getDate() + days);
            var month = d.getMonth() + 1;
            var day = d.getDate();
            var w = d.getDay();
            var daysArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            month = (month < 10) ? "0" + month : month;
            day = (day < 10) ? "0" + day : day;
            var val =  month + "月" + day+ "日  " +daysArr[w];
            return val;
        },
        // setSlots() {  
        //     //获取当前时间，判断是否大于16:00；
        //     console.log(this);
        //     console.log(this.currentTime);
        //     time=this.currentTime;
        //     console.log(time);
        //     var h = time.getHours();
        //     if(h<=16){
        //       this.defaultIndex=1;
        //     }else{
        //       this.defaultIndex=2
        //     }
        //     return [
        //       {
        //         flex:1,
        //         values: this.getDaysArr(this.num),
        //         className: 'slot1',
        //         textAlign: 'center',
        //         defaultIndex:parseInt(sessionStorage.getItem("defaultIndex"))?parseInt(sessionStorage.getItem("defaultIndex")):this.defaultIndex
        //       }, {
        //         flex: 1,
        //         values: ["上午","下午"],
        //         className: 'slot2',
        //         textAlign: 'center'
        //       }
        //     ]
        // },
        
        onChange(picker, values){
          //获取当前时间，判断是否大于16:00
          var time = new Date(this.currentTime);
          var h = time.getHours();
          var arr = this.getDaysArr(this.num);
          var v = picker.getSlotValue(0);
          var index = 0;
          for(var i=0; i<arr.length;i++){
            if(v==arr[i]){
                  index=i;
            }
          }
          if(h<16){
            if(!this.isscode){
              if (index==0) {
                picker.setSlotValues(1,['需门店确认']);
                try {
                  setTimeout(function () {
                    document.getElementsByClassName('picker-selected')[1].style.color = 'red';
                  }, 0);
                } catch(e) {};
              }else{
                picker.setSlotValues(1,["上午","下午"]);
              }
            }else{
              if(index<=2){
                picker.setSlotValues(1,['需门店确认']);
                try {
                  setTimeout(function () {
                    document.getElementsByClassName('picker-selected')[1].style.color = 'red';
                  }, 0);
                } catch(e) {};
              }else{
                picker.setSlotValues(1,["上午","下午"]);
              }
            }
            
          }else{
            if(!this.isscode){
              if(index<=1){
                picker.setSlotValues(1,['需门店确认']);
                try {
                	setTimeout(function () {
  	              	document.getElementsByClassName('picker-selected')[1].style.color = 'red';
  	              }, 0);
                } catch(e) {};
              }else{
                picker.setSlotValues(1,["上午","下午"]);
              }
            }else{
              if(index<=3){
                picker.setSlotValues(1,['需门店确认']);
                try {
                  setTimeout(function () {
                    document.getElementsByClassName('picker-selected')[1].style.color = 'red';
                  }, 0);
                } catch(e) {};
              }else{
                picker.setSlotValues(1,["上午","下午"]);
              }
            }
          }
          this.defaultIndex = index;
          this.currentValue = picker.getValues();
          this.remark = picker.getSlotValue(1);
          
          },
            open(){
              this.popupVisible = !this.popupVisible;
            },
            cancel() {
                this.popupVisible = !this.popupVisible
            },
            confirm(){
                this.popupVisible = !this.popupVisible;  
                //var cv = JSON.stringify(this.currentValue);
                //console.log(new String(this.currentValue).split(",")[0],12132312);
                
                var cv = new String(this.currentValue).split(",");

                var cv1 = cv[1]?cv[1]:" ";
                var c = cv[0]+" "+cv1;
                document.getElementById("gotoStore").value = c;
                if(window.sessionStorage){
                   //sessionStorage.setItem("defaultIndex",this.defaultIndex);
                   sessionStorage.setItem("currentValue",cv[0]+" "+cv1);

                   var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");

                   if(reg.test(this.fullDaysArr[this.defaultIndex])){
                    var str = this.fullDaysArr[this.defaultIndex].replace(/([^\u0000-\u00FF])/g,'/');
                    this.chooseTime = str.substring(0,str.length-1);

                   }else{
                    this.chooseTime = this.fullDaysArr[this.defaultIndex].replace(/([^\u0000-\u00FF])/g,'/');
                   }
                  // return reg.test(this.fullDaysArr[this.defaultIndex]) ? true : false;


                   // console.log(this.chooseTime);
                   sessionStorage.setItem("fullday",this.chooseTime);
                   this.$dispatch("chooseTime-dispatch");
                   sessionStorage.setItem('remark',this.remark);
                   //this.$emit("fullday",this.fullDaysArr[this.defaultIndex])
                   //this.$parent.$refs.coupon.chooseTime = sessionStorage.getItem("fullday");
                }else{
                   console.log("don't support sessionStorage");
                }
            },
        /**
         *  去除前后空格
         * @param {String} str
         * @reutrn {String} 
         */
        trim: function ( str ) {
        	if ( str ) {
			    return str.replace(/(^\s*)|(\s*$)/g, "");
        	}
        	return '';
		}    
    },
    

  };
</script>

